//
//  CertificationViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/31.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "CertificationViewController.h"
#import "QFMultimedia.h"
#import "AlertMessageView.h"
#import "EGOImageView.h"
#import "ASIFormDataRequest.h"
@interface CertificationViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>{
    int photo;
}
@property (nonatomic,strong) NSMutableDictionary *data;
@end

@implementation CertificationViewController
@synthesize isShowMessage,data;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"认证资料";
    [self.leftBtn addTarget: self action: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];
    [self.view setBackgroundColor:UIColorFromRGB(0xf3f2f2)];
    photo = 0;
    NSMutableDictionary *json = [self getMylicense];
    if ([[json objectForKey:@"err_code"] integerValue]!=0) {
        SHOW_ALERT([json objectForKey:@"err_message"]);
        return;
    }
    self.data = [NSMutableDictionary dictionary];
    self.data = [json objectForKey:@"data"];
    self.isShowMessage = [[data objectForKey:@"status"] integerValue];
//    self.isShowMessage = 0;
    int messageHeight = 0;
    if (self.isShowMessage != 0) {
        messageHeight = 25;
        [self.rightBtn setTitle:@"" forState:0];
        [self superMainVC:25];
        
    }else{
        [self.rightBtn setTitle:@"提交" forState:0];
        [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
        [self.rightBtn addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
        [self.rightBtn setEnabled:NO];
        [self drawMainView:0];
    }
    
    
    // Do any additional setup after loading the view.
}
-(void)superMainVC:(int)height{
    if (self.mainView) {
        [self.mainView removeFromSuperview];
    }
    UIView *tempMainView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SWIDTH, VHEIGHT)];
    [tempMainView setBackgroundColor:[UIColor clearColor]];
    self.mainView = tempMainView;
    self.mainView.backgroundColor = UIColorFromRGB(0xf3f2f2);
    [self.view addSubview:self.mainView];
    
    if ([Unity isBlankString:[self.data objectForKey:@"message"]]) {
        height = 0;
    }
    
    UILabel *lab = [self createLabelFrame:CGRectMake(10, height+8, SWIDTH - 20, 20) title:@"营业执照" titleColor:BLACKColor tag:0];
    lab.font = [UIFont systemFontOfSize:14];
    [self.mainView addSubview:lab];
    
    EGOImageView *image = [self createImageViewFrame:CGRectMake((SWIDTH - 240)/2, 34+height, 240, 264) image:nil imageName:@"" imageUrl:[self.data objectForKey:@"license_file"] tag:101];
    image.contentMode = UIViewContentModeScaleAspectFit;
    [self.mainView addSubview:image];
    
    UIButton *loginBtn = [self createButtonFrame:CGRectMake(20, 316+height, SWIDTH - 40, 43) title:@"更换图片" viewController:self selector:@selector(pictureClick:) tag:102];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"登录-点击后按钮"] forState:UIControlStateNormal];
    [self.mainView addSubview:loginBtn];
    
    if (self.isShowMessage!=0) {
        AlertMessageView *messageView = [[AlertMessageView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, 25)];
        messageView.backgroundColor = GREENColor;
        messageView.tempLab.font = [UIFont systemFontOfSize:12];
        messageView.tempLab.text = [self.data objectForKey:@"message"];
        [self.mainView addSubview:messageView];
        if ([Unity isBlankString:[self.data objectForKey:@"message"]]) {
            [messageView setHidden:YES];
        }
        switch (self.isShowMessage) {
            case -1:
                messageView.backgroundColor = UIColorFromRGB(0xde5826);
                [loginBtn setTitle:@"重新上传" forState:0];
                [self.rightBtn setTitle:@"提交" forState:0];
                [self.rightBtn setTitleColor:ButtonGrayColor forState:0];
                [self.rightBtn addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
                [self.rightBtn setEnabled:NO];
                break;
            case 1:
                [loginBtn setHidden:YES];
                break;
            case 2:
                [loginBtn setHidden:YES];
                break;
            default:
                break;
        }
    }
}
- (EGOImageView *)createImageViewFrame:(CGRect)frame
                                image:(UIImage *)image
                            imageName:(NSString *)imageName
                              imageUrl:(NSString *)url
                                  tag:(NSInteger)tag{
    NSURL *urlStr = [NSURL URLWithString:url];
    EGOImageView *tempImageView = [[EGOImageView alloc]initWithPlaceholderImage:[UIImage imageNamed:@"缺省图"]];
    tempImageView.frame = frame;
    [tempImageView setBackgroundColor:[UIColor clearColor]];
    if (image) {
        tempImageView.image = image;
    }
    if (![imageName isEqualToString:@""]){
        tempImageView.image = [UIImage imageNamed:imageName];
    }
    if (![url isEqualToString:@""]) {
        [tempImageView setImageURL:urlStr];
    }
    [tempImageView setTag:tag];
    return tempImageView;
}

/**
 *  获取认证
 *
 *  @param body 为空
 */
-(NSMutableDictionary *)getMylicense{
    TIME
    HEADDIC(nowTime, MYLICENSE);
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSMutableDictionary *dict = [result objectFromJSONString];
    return dict;
}
-(void)drawMainView:(int)height{
    UILabel *lab = [self createLabelFrame:CGRectMake(10, 15+height, SWIDTH - 20, 20) title:@"营业执照" titleColor:BLACKColor tag:0];
    lab.font = [UIFont systemFontOfSize:14];
    [self.mainView addSubview:lab];
    
    UIButton *button = [self createButtonFrame:CGRectMake(10, 45+height, SWIDTH - 20, 42) title:@"上传营业执照" viewController:self selector:@selector(pictureClick:) tag:0];
    [button setTitleColor:GRAYColor forState:0];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [button setBackgroundColor:[UIColor whiteColor]];
    [self.mainView addSubview:button];
    
    UIImageView *imageV = [self createImageViewFrame:CGRectMake(120-25, (42 - 17)/2, 23, 17) image:nil imageName:@"相机.png" tag:0];
    [imageV setBackgroundColor:[UIColor clearColor]];
    [button addSubview:imageV];
}
-(void)submit:(UIButton *)sender{
//    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提交成功" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    alert.tag = 255;
//    [alert show];
    [self upLoadFile];
}
-(void)upLoadFile{
    TIME
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",APPIP,SETLICENSE];
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *imagefile = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/mylicense.jpg"];
    ASIFormDataRequest *uploadFileRequest = [ASIFormDataRequest requestWithURL:url];
    [uploadFileRequest setStringEncoding:NSUTF8StringEncoding];
    [uploadFileRequest setRequestMethod:@"POST"];
    [uploadFileRequest addPostValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"certificate"] forKey:@"certificate"];
    [uploadFileRequest addPostValue:nowTime forKey:@"client_ts"];
    [uploadFileRequest addData:imagefile withFileName:@"mylicense.jpg" andContentType:nil forKey:@"imagefile"];
    uploadFileRequest.delegate = self;
    [uploadFileRequest setDidFinishSelector:@selector(responseFinish:)];
    [uploadFileRequest setDidFailSelector:@selector(responseFail:)];
    [uploadFileRequest startAsynchronous];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
-(void)responseFinish:(ASIFormDataRequest *)request{
    NSLog(@"resquest__%@",request.responseString);
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSDictionary *dic = [request.responseString objectFromJSONString];
    NSString *message = [dic objectForKey:@"err_message"];
    if ([[dic objectForKey:@"err_code"] stringValue]==0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 255;
        [alert show];
    }else{
        SHOW_ALERT(message);
    }
}

-(void)responseFail:(ASIFormDataRequest *)request{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSLog(@"error__%@",request.error);
}
-(void)goBack{
//    NSFileManager* fileManager=[NSFileManager defaultManager];
//    NSString *imagefile = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/mylicense.jpg"];
//    if([fileManager removeItemAtPath:imagefile error:nil])
//    {
//        NSError *err;
//        [fileManager removeItemAtPath:imagefile error:&err];
//        NSLog(@"删除");
//    }
//    [self.navigationController popViewControllerAnimated:YES];
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 255) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(void)pictureClick:(UIButton *)sender{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"从手机选择",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSUInteger sourceType = 0;
    // 判断是否支持相机
    switch (buttonIndex) {
        case 0:
            // 相机
            sourceType = UIImagePickerControllerSourceTypeCamera;
            [self takePhoto:sourceType];
            break;
        case 1:
            // 相册
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self takePhoto:sourceType];
            break;
    }
    
}
-(void)takePhoto:(NSUInteger)sourceType{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    //    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:^{}];
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
//    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
//    
//    //当选择的类型是图片
//    if ([type isEqualToString:@"public.image"])
//    {
//        //先把图片转成NSData
//        UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
//        NSData *data ;//= [QFMultimedia compress:image ratio:0.5 quality:0.5];
//        //        [data writeToFile:imagePath atomically:YES];
//        
//        //        if (UIImagePNGRepresentation(image) == nil)
//        //        {
//        //            data = UIImageJPEGRepresentation(image, 1.0);
//        //        }
//        //        else
//        //        {
//        //            data = UIImagePNGRepresentation(image);
//        //        }
//        CGFloat ratio = 1;
//        if (image.size.width > 640) {
//            ratio = 640 / image.size.width;
//        } else if (image.size.height > 960){
//            ratio = 960 / image.size.height;
//        }
//        data = [QFMultimedia compress:image ratio:ratio quality:0.6];
//        if (data == nil) {
//            return;
//        }
//        
//        //图片保存的路径
//        //这里将图片放在沙盒的documents文件夹中
//        //        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//        //
//        //        //文件管理器
//        //        NSFileManager *fileManager = [NSFileManager defaultManager];
//        //
//        //        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
//        //        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
//        //        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/123.png"] contents:data attributes:nil];
//        //
//        //        //得到选择后沙盒中图片的完整路径
//        //        self.filePath = [NSString stringWithFormat:@"%@%@",DocumentsPath,  @"/123.png"];;
//        //        NSLog(@"filePath___%@",self.filePath);
//        //关闭相册界面

    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *imageName = [NSString stringWithFormat:@"mylicense.jpg"];
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    [self saveImage:image withName:imageName];
    if (self.isShowMessage == 0) {
        [self superMainVC:0];
    }else{
        [self superMainVC:25];
    }
    
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    EGOImageView *imageView = (EGOImageView *)[self.mainView viewWithTag:101];
    if (savedImage !=nil) {
        [self.rightBtn setTitleColor:WhiteColor forState:0];
        [self.rightBtn setEnabled:YES];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        [imageView setImage:savedImage];
    }];
    
}
-(void)saveImage:(UIImage*)currentImage withName:(NSString*)imageName{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.3);
    NSString *fullPath =[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName ];
    [imageData writeToFile:fullPath atomically:NO];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    photo = 0;
    NSLog(@"您取消了选择图片");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
